<script setup lang='ts'>
import { ref } from 'vue'
import { useMessage } from 'naive-ui'
import AvatarComponent from './Avatar.vue'
import TextComponent from './Text.vue'
import { SvgIcon } from '@/components/common'
import { t } from '@/locales'
import { copyToClip } from '@/utils/copy'

interface Props {
  dateTime?: string
  text?: string
  isUser?: boolean
  error?: boolean
}

const props = defineProps<Props>()

const message = useMessage()

const textRef = ref<HTMLElement>()

const messageRef = ref<HTMLElement>()

async function handleCopy() {
  try {
    await copyToClip(props.text || '')
    message.success(t('chat.copied'))
  }
  catch {
    message.error(t('chat.copyFailed'))
  }
}
</script>

<template>
  <div
    ref="messageRef"
    class="mb-6 w-full flex overflow-hidden"
    :class="[{ 'flex-row-reverse': isUser }]"
  >
    <div>
      <div
        class="h-8 flex flex-shrink-0 basis-8 items-center justify-center overflow-hidden rounded-full"
        :class="[isUser ? 'ml-2' : 'mr-2']"
      >
        <AvatarComponent :image="isUser" />
      </div>
      <p v-show="isUser" class="ml-1 mt-1 text-center text-xs text-green-500">
        zhangsan
      </p>
    </div>

    <div class="overflow-hidden text-sm" :class="[isUser ? 'items-end' : 'items-start']">
      <p class="text-xs text-[#b4bbc4]" :class="[isUser ? 'text-right' : 'text-left']">
        {{ dateTime }}
      </p>
      <div
        class="mt-2 flex items-end gap-1"
        :class="[isUser ? 'flex-row-reverse' : 'flex-row']"
      >
        <TextComponent
          ref="textRef"
          :is-user="isUser"
          :error="error"
          :text="text"
        />
        <div class="flex flex-col">
          <span
            v-if="!isUser"
            class="mb-2 cursor-pointer text-neutral-300 transition hover:text-neutral-700 dark:hover:text-neutral-400"
            @click="handleCopy"
          >
            <SvgIcon icon="ri:file-copy-2-line" />
          </span>
        </div>
      </div>
    </div>
  </div>
</template>
